﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ScannerSuccessRate.Helper
{
    public class ScannerHelper
    {
        /// <summary>
        /// 读取条码
        /// </summary>
        /// <param name="ipString"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public static string read(string ipString, int port)
        {
            Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(ipString);
            IPEndPoint point = new IPEndPoint(ip, port);
            socketWatch.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000);
            //绑定IP地址和端口号
            try
            {
                socketWatch.Connect(point);
                socketWatch.ReceiveTimeout = 5000;
                byte[] buffer = new byte[2048];
                // 发送开始读条码的信息
                string smsg = "SA";
                byte[] msgSend = System.Text.Encoding.UTF8.GetBytes(smsg);
                int resInt = socketWatch.Send(msgSend);
                int count = socketWatch.Receive(buffer);
                return System.Text.Encoding.UTF8.GetString(buffer).Trim();
            }
            catch
            {
                MyLogHelper.LogError("连接扫码器失败,扫码器IP" + ipString);
                //socketWatch.Close();
            }
            //finally
            //{
            //    socketWatch.Close();
            //}
            // 如果未读到条码则返回NoRead,注意 "SA" 和 "Noread"可以在扫码器的软件中自定义
            return "Noread";
        }
    }
}
